<template>
  <div class="wrapper" v-if="detail[0]">
    <div class='top'>
      <h3>{{ orderStatus.title }}</h3>
      <h5>订单金额(含运费): ￥{{ detail[0] && detail[0].subtotal }}</h5>
      <h5 v-if="orderStatus.status != 4">
        <Timeout :time="orderStatus.time" :desc="orderStatus.desc" />
      </h5>
    </div>
    <Logistics v-if="logis" :logis="logis" />
    <OrderAddress
      :name="detail[0].addressname"
      :mobile="detail[0].mobile"
      :province="detail[0].province"
      :city="detail[0].city"
      :district="detail[0].district"
      :address="detail[0].address"
    />
    <div class="goods-list">
      <p class="title">有惊喜</p>
      <GoodsItem
        v-for="(item, index) of detail"
        :title="item.name"
        :price="item.total || item.price"
        :count="Number(item.order_num)"
        :img="item.url"
        :key="index"
      >
        <router-link
          :to="'/center/orderDetailReturn/' + item.order_code + '/' + index"
          v-if="item.shipping_status == 6"
          tag="button"
          class="btn"
        >
          退货
        </router-link>
        <span class="desc color-red" v-if="item.shipping_status == 5">
          退货中...
        </span>
        <span class="desc color-red" v-if="item.shipping_status == 7">
          已退货
        </span>
      </GoodsItem>
    </div>
    <div class="mid">
      <MsgItem title="商品小计" :value="'￥' + detail[0].subtotal"></MsgItem>
      <MsgItem title="运费" value="￥0.00"></MsgItem>
      <MsgItem title="实付费(含运费)" :value="'￥' + detail[0].subtotal" :highLight="true"></MsgItem>
      <MsgItem title="买家备注" :value="detail[0].remark || '无'"></MsgItem>
    </div>
    <div class="bottom">
      <p>订单编号：{{ detail[0].order_code }}</p>
      <p>创建时间：{{ detail[0].create_at }}</p>
      <p>支付时间：{{ detail[0].create_at }}</p>
    </div>
    <div class="bar" v-if="detail[0].payment_status == 1">
      <button class="back" @click="beforePay">立即付款</button>
      <template v-if="this.userState == 2">
        <button class="back" @click="balancePay">余额付款</button>
        <span class="color-red">余额：￥{{ balance }}</span>
      </template>
    </div>
    <div class="bar" v-else-if="detail[0].payment_status == 2 && detail[0].shipping_status == 2">
      <router-link :to="'/center/orderList/orderDetail/refund/' + $route.params.id" tag="button" class="back">申请退款</router-link>
    </div>  
    <div class="bar" v-else-if="detail[0].shipping_status == 6">
      <button class="back" @click="confirm">确认收货</button>
    </div>
  </div>
</template>

<script>
  import _ from 'lodash'
  import GoodsItem from '@/components/goodsItem/GoodsItem.vue'
  import Logistics from '@/components/logistics/Logistics.vue'
  import Timeout from '@/components/timeout/Timeout.vue'
  import MsgItem from '@/components/msgItem/MsgItem.vue'
  import OrderAddress from '@/components/orderAddress/OrderAddress.vue'
  import { mapState } from 'vuex'
  export default {
    name: 'OrderDetail',
    components: {
      GoodsItem,
      Logistics,
      Timeout,
      MsgItem,
      OrderAddress
    },
    created() {
      this._get()
      if (this.userState == 2) {
       this._getBalance()
      }
    },
    data() {
      return {
        detail: [],
        logis: '',
        balance: ''
      }
    },
    computed: {
      ...mapState(['openId', 'userState']),
      apiUrl() {
        return this.userState == 0 ? '/v1/merchant/show' : '/v1/platform/show'
      },
      orderStatus() {
        let status = ''
        let title = ''
        let desc = ''
        let time = ''
        this.detail.forEach(item => {
          if(item.payment_status == 1) {
            status = 1
            title = '买家未付款'
            desc = '后不付款订单自动取消'
            time = this.detail[0].payment_endtime
            return
          }
          if(item.payment_status == 2) {
            if(item.shipping_status == 2) {
              status = 2
              title = '等待卖家发货'
              desc = '后商家不发货,会重新安排新的商家发货,请耐心等待'
              time = this.detail[0].not_endtime
              return
            }
            if(item.shipping_status == 4) {
              status = 4
              title = '订单已完成'
              desc = ''
              time = ''
              return
            }
            if(item.shipping_status == 6) {
              status = 6
              title = '卖家已发货'
              desc = '后自动确认收货'
              time = this.detail[0].confirm_endtime
              return
            }
          }
        })
        return { status, title, desc, time }
      }
    },
    methods: {
      async _get() {
        let { data: { code, data } } = await this.$axios({
          url: this.apiUrl,
          method: 'GET',
          params: {
            order_code: this.$route.params.id,
            openid: this.openId
          }
        })
        if(code === 0) {
          this.detail = data
          if(this.detail[0].shipping_status != '2') {
            this.getLogistics(this.detail[0].com, this.detail[0].num)
          }
        }
      },
      async getLogistics(com, num) {
        let { data: { code, data } } = await this.$axios({
          url: '/v1/platform/expre',
          method: 'GET',
          params: {
            com,
            num
          }
        })
        if(code === 0) {
          if (Array.isArray(data)) {
            let logisArr = data[0].data.map(item => {
              item.day = item.time.substring(5, 10)
              item.time = item.time.substring(11, 16)
              return item
            })
            this.logis = {
              com: data[0].com,
              num: data[0].nu,
              logisArr
            }
          } else {
            this.logis = data
          }
        }
      },
      async _getBalance() {
        try{
          let { data: { code, data } } = await this.$axios({
            url: '/v1/platform/balance',
            method: 'GET',
            params: {
              openid: this.openId
            }
          })
          if (code === 0) {
            this.balance = data
          } else if(code === 1) {
            this.balance = 0
          }
          this.$toast.clear()
        }catch(e){
          this.$toast(e)
        }
      },
      async confirm() {
        this.$confirm('是否确认收货?').then(() => {
          this._confirm()
        })
      },
      _confirm: _.throttle(async function() {
        let { data: { code, data } } = await this.$axios({
          url: '/v1/merchant/confirm',
          method: 'POST',
          data: {
            order_code: this.$route.params.id,
            openid: this.openId
          }
        })
        if (code === 0) {
          this.$toast(data)
          setTimeout(() => {
            this.$router.go(-1)
          }, 1500)
        }
      }, 2000, { trailing: false }),
      balancePay() {
        if (this.balance < this.detail[0].subtotal) {
          this.$toast('余额不足')
          return
        }
        this.$confirm('使用余额支付？').then(() => {
          this._balancePay()
        })
      },
      async _balancePay() {
        let { data: { code } } = await this.$axios({
          url: '/v1/platform/pay',
          method: 'POST',
          data: {
            order_code: this.detail[0].order_code,
            subtotal: Number(this.detail[0].subtotal),
            openid: this.openId
          }
        })
        if (code === 0) {
          this.$router.replace('/payComplete')
        }
      },
      async beforePay() {
        let formData = new FormData()
        formData.append('uid', this.detail[0].user_id)
        formData.append('oid', this.detail[0].id)
        formData.append('totalFee', Number(this.detail[0].subtotal))
        formData.append('orderName', 'WowSurprise有惊喜')
        formData.append('openid', this.openId)
        formData.append('outTradeNo', this.detail[0].order_code)
        let { data: { code, data } } = await this.$axios({
          url: '/v1/wechat/pay',
          method: 'POST',
          data: formData
        })
        if(code === 0) {
          this.$toast.loading({
            message: 'Loading...',
            forbidClick: true,
            loadingType: 'spinner',
            duration: 0
          })
          this.Pay(data.package)
        }
      },
      Pay (data) {
        let vm = this
        if (typeof WeixinJSBridge === 'undefined') {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false)
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data))
            document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data))
          }
        } else {
          vm.onBridgeReady(data)
        }
      },
      onBridgeReady (data) {
        this.$toast.clear()
        let self = this
        /* eslint-disable */
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            'appId': data.appId,
            'timeStamp': String(data.timeStamp),    //这里必须要转换为字符串。ios跟android表现不同。后台返回的是数值，但是微信方面必须要json参数都是字符串形式，android会自动转换成字符串（当时我在这里也找了很久的博文才知道的）
            'nonceStr': data.nonceStr,
            'package': data.package,
            'signType': data.signType,
            'paySign': data.paySign
          },
          function (res) {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              // self.$router.replace('/payComplete')
              window.location.href = 'http://www.youjingxi.net.cn/h5/#/payComplete'
            } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              self.$toast('支付取消!')
            } else {
              self.$toast('支付失败!')
            }
          }
        )
        /* eslint-enable */
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '@/assets/css/base.scss';
  .wrapper {
    min-height: 100vh;
    background: #eee;
    padding-bottom: 50px;
  }
  .top {
    text-align: center;
    margin-bottom: 0.2rem;
    padding: 0.6rem 0;
    background: orange;
    color: #fff;
    h3 {
      font-size: 0.32rem;
    }
    h5 {
      font-size: 0.28rem;
    }
  }
  .goods-list {
    padding: 0 0.2rem;
    background: #FFF;
    .title {
      padding: 0.1rem 0;
      font-size: 0.24rem;
      border-bottom: 1px solid $bgGray;
    }
  }
  .mid {
    margin-top: 0.2rem;
    padding: 0 0.2rem;
    background: #fff;
  }
  .bottom {
    margin-top: 0.2rem;
    padding: 0.2rem;
    background:#fff;
    p {
      margin-bottom: 0.1rem;
      font-size: 0.24rem;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  .bar {
    margin-top: 0.2rem;
    background: #fff;
    padding: 0.2rem;
    text-align: right;
    .back {
      margin-right: 0.1rem;
      padding: 0.1rem;
      border: 1px solid $colorGray;
      background: $bgGray;
      border-radius: 20px;
    }
  }
</style>
